<template>
  <div class="v-editor-name-uni g-pd-l-8">
    <el-checkbox
      v-model="checked"
      :label="$t(label)"
      size="small"
      :indeterminate="indeterminate"
      :disabled="props.row.readonly || isModelDisabled"
      @change="handleChange"
    ></el-checkbox>
  </div>
</template>

<script lang="ts" setup>
import { PropertyRow } from "../../types";
import { Ref, computed, inject, ref, watch } from "vue";
import { modelService } from "@/modules/model/service";
import { PropertyKey } from "@/constants/Enums";
import { ModelData } from "@/mdesign-lib/mdesign-app.umd.js";

const isModelDisabled = inject("isModelDisabled") as Ref<boolean>;

const props = defineProps<{
  row: PropertyRow;
  selected?: boolean;
}>();

const map = new Map([
  [true, "是"],
  [false, "否"],
  [null, "空"]
]);

const checked = ref(props.row.value as boolean);
const label = computed(() => {
  return map.get(checked.value) || "空";
});
const indeterminate = computed(() => {
  return props.row.value === null;
});

watch(
  () => props.row.value,
  () => {
    checked.value = props.row.value as boolean;
  }
);

let parentId = "";
let applyToElements: string[] = [];
let defaultName = "";
let prefixRule = "";
let separator = "";
let prefix = "";

// 获取最新属性
async function getParamDefaultValue() {
  const list = await modelService.getModelProperties(app.activeProjectId, props.row.modelId);
  let ownerValue = list.find(item => item.key === PropertyKey.Element_owner)?.value as ModelData;
  parentId = ownerValue.id;

  list.forEach(item => {
    switch (item.key) {
      case PropertyKey.Customization_NamingRule_applyToElements:
        {
          let applyToElementsValue = item.value as ModelData[];
          applyToElements = applyToElementsValue.map(it => it.id) || [];
        }
        break;

      case PropertyKey.Customization_NamingRule_defaultName:
        defaultName = item.value as string;
        break;

      case PropertyKey.Customization_NamingRule_prefixRule:
        {
          let prefixRuleValue = item.value as ModelData;
          prefixRule = prefixRuleValue ? prefixRuleValue.id : "";
        }
        break;

      case PropertyKey.Customization_NamingRule_separator:
        separator = item.value as string;
        break;

      case PropertyKey.Customization_NamingRule_prefix:
        prefix = item.value as string;
        break;

      default:
        break;
    }
  });
}

async function handleChange(value: boolean) {
  await getParamDefaultValue();

  await modelService.batchUpdateNamingRule({
    projectId: app.activeProjectId,
    parentId,
    namingRules: [
      {
        dataType: "update",
        nameRuleId: props.row.modelId,
        applyToElements,
        isNameUni: value,
        defaultName,
        prefixRule,
        separator,
        prefix
      }
    ]
  });
}
</script>

<style lang="scss" scoped>
.v-editor-name-uni {
}
</style>
